package com.example.module_patrol

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.PopupMenu
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.base.BaseActivity
import com.example.lib_common.utils.ToastUtils
import com.example.module_patrol.adapter.PatrolAdapter
import com.example.module_patrol.databinding.ActivityPatrolBinding
import com.example.module_patrol.ui.PatrolViewmodel
import dagger.hilt.android.AndroidEntryPoint
@Route(path = "/patrol/PatrolActivity")
@AndroidEntryPoint
class PatrolActivity : BaseActivity<PatrolViewmodel,ActivityPatrolBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_patrol
    private val mViewModel: PatrolViewmodel by viewModels()
    lateinit var pkAdapter: PatrolAdapter
    private var back: ImageView? = null
    private var more: ImageView? = null

    override fun initView() {
        pkAdapter = PatrolAdapter()
        mBinding.rv.adapter = pkAdapter
        mBinding.rv.layoutManager = LinearLayoutManager(this)
        //根据车位类型获取车位信息
        mViewModel.getPatrolList()
        /*
        返回键
         */
        back=mBinding.topBar1.findViewById(R.id.back)
        back!!.setOnClickListener {
            finish()
        }
        /*
        更多：新增点位
         */
        more=mBinding.topBar1.findViewById(R.id.more)
        more!!.setOnClickListener {
            showPopupMenu(more!!)
        }

        // 加载原始数据
        loadOriginalData();

        // 设置搜索监听
        setupSearchFunctionality();

        mBinding.shang1.setOnClickListener {
            ToastUtils.showShort(this,"暂不可用")
        }
        mBinding.shang3.setOnClickListener {
            ToastUtils.showShort(this,"暂不可用")
        }
        mBinding.shang4.setOnClickListener {
            ToastUtils.showShort(this,"暂不可用")
        }

    }
    private fun performSearch() {
        //3156
        mViewModel.searchPatrol(mBinding.search.text.toString(),"点位1")

        mViewModel.searchPatrolLiveData.observe(this) {
            if (it == null) {
                ToastUtils.showLong(this, "没有数据") // 显示空状态
            } else {
                pkAdapter.addParkingList(it)
            }

        }
    }

    private fun setupSearchFunctionality() {
        // 1. 回车键搜索
        mBinding.search.setOnEditorActionListener { v, actionId, event ->
            if (actionId === EditorInfo.IME_ACTION_SEARCH ||
                (event != null && event.getKeyCode() === KeyEvent.KEYCODE_ENTER)
            ) {
                performSearch()
                return@setOnEditorActionListener true
            }
            false
        }

        // 2. 文本变化监听，当清空时恢复原始列表
        mBinding.search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.toString().trim { it <= ' ' }.isEmpty()) {
                    // 搜索框内容被清空，恢复原始列表
                    mViewModel.getPatrolList()
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })

    }

    private fun loadOriginalData() {
        mViewModel.patrolListLiveData.observe(this) {
            if (it.isNullOrEmpty()) {
                ToastUtils.showLong(this, "没有数据") // 显示空状态
            } else {
                pkAdapter.addParkingList(it)
            }
        }
    }

    fun showPopupMenu(view: View) {
        val popup = PopupMenu(this, view) // view 是锚点视图（被点击的按钮等）
        popup.menuInflater.inflate(R.menu.menu_more, popup.menu)

        // 处理菜单项点击
        popup.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.add -> {
                    ARouter.getInstance().build("/patrol/AddPatrolActivity").navigation()
                    true
                }
                R.id.notDoing->{
                    ARouter.getInstance().build("/patrol/NotDoingActivity").navigation()
                    true
                }
                R.id.more -> {
                    ToastUtils.showShort(this, "更多功能正在开发中...")
                    true
                }
                else -> false
            }
        }

        // 显示菜单
        popup.show()
    }

    override fun initData() {

    }



}